//
//  InvestorDetailMessageController.m
//  BigToBig
//
//  Created by yi liu on 16/7/28.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "InvestorDetailMessageController.h"
#import "InvestorDetailMessageView.h"
#import "DetailInfoCell.h"
#import "BasicInfoTableViewCell.h"
#import "ProjectDetailViewController.h"
#import "FocusProjectModel.h"

@interface InvestorDetailMessageController ()
<
    UITableViewDelegate,
    UITableViewDataSource
>

@property (nonatomic , strong)InvestorDetailMessageView *investorDetailMessageView;

@property (nonatomic , strong)UITableView *mainTableView;


@property (nonatomic , strong)UIButton *focusButton;
@property (nonatomic , strong)NSArray *planArray;
@property (nonatomic , strong)NSArray *content;

@property (nonatomic , strong)NSString *info;

@property (nonatomic , assign)BOOL isSelected;
@property (nonatomic , assign)NSInteger projectCount;

@property (nonatomic , strong)NSMutableArray *modelArr;
@property (nonatomic , assign)NSInteger isFocused;

@end

@implementation InvestorDetailMessageController

- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    [self ifFocusThisGuy];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createData];
    [self focusProjectModel];
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    titleLab.text = self.model.name;
    titleLab.textColor = [UIColor whiteColor];
    [self setBackBar];
    titleLab.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLab;
    [self createView];

    
}

#pragma mark 创建数据
- (void)createData{
    self.planArray = @[@"关注领域",@"关注城市",@"每年计划投资项目个数"];
    self.info = _model.selfIntroduction;
    self.content = @[@"最高学历",@"投资理念",@"关注项目"];
    self.projectCount = 0;
}
- (void)focusProjectModel{
    self.modelArr = [NSMutableArray new];

    NSDictionary *params = @{@"user_id":_model.user_id};
    NSString *urlStr = [NSString stringWithFormat:@"http://61.135.176.43:6080/bigtobig/notice_project/show_project?user_id=%@&offset=0&limit=10",_model.user_id];
    [HttpTool textHTMLPostWithURL:urlStr params:params success:^(id json) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSNumber *count = [dict objectForKey:@"count"];
        NSArray *noticeProjectsArr = [dict objectForKey:@"notice_projects"];
        for (NSDictionary *dic in noticeProjectsArr) {
            FocusProjectModel *focusModel = [FocusProjectModel FocusProjectModelWithDict:dic];
            [self.modelArr addObject:focusModel];
        }
        self.projectCount = self.projectCount + count.integerValue;
        [self.mainTableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}
- (void)ifFocusThisGuy{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *follower_id = [userDefault objectForKey:@"userID"];
    NSString *follow_id = self.model.user_id;
    NSDictionary *params = @{@"follow_id":follow_id,@"follower_id":follower_id};
    [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/relation/show_relation?" params:params success:^(id json) {
        NSString *type = [json objectForKey:@"type"];
        self.isFocused = type.integerValue;
        // 关注按钮
        self.focusButton = [UIButton  buttonWithType:UIButtonTypeSystem];
        self.focusButton.frame = CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49);
        [self.view addSubview:self.focusButton];
        [self.focusButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        if (self.isFocused) {
            
            [self.focusButton setTitle:@"关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = COLOR_RGBA(255, 81, 90, 1);
        }
        else{
            [self.focusButton setTitle:@"取消关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = [UIColor lightGrayColor];
        }
        
        NSLog(@"%ld",self.isFocused);
        [self.focusButton addTarget:self action:@selector(focusButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        
    } failure:^(NSError *error) {
        
        
    }];
    
}


- (void)focusButtonAction:(UIButton *)button{
    //    relation/add_follower?follow_id=6&follower_id=9
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *follow_id = [userDefault objectForKey:@"userID"];
    NSString *follower_id = self.model.user_id;
    NSDictionary *params = @{@"follow_id":follow_id,@"follower_id":follower_id};
    if (self.isFocused == 1) {
        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/relation/add_follower?" params:params success:^(id json) {
            [self.focusButton setTitle:@"取消关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = [UIColor lightGrayColor];
            self.isFocused = 0;
            
        } failure:^(NSError *error) {
            
            
        }];
    }
    else{
        
        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/relation/cancel_follower?" params:params success:^(id json) {
            [self.focusButton setTitle:@"关注" forState:UIControlStateNormal];
            self.focusButton.backgroundColor = COLOR_RGBA(255, 81, 90, 1);
            self.isFocused = 1;
            
        } failure:^(NSError *error) {
            
            
        }];
    }
    
}

#pragma mark 导航栏左右Button
- (void)setBackBar{
    
    BackButton *backBtn=[BackButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 44, 44);
    [backBtn addTarget:self action:@selector(backController:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn.imageView setContentMode:UIViewContentModeLeft];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    [self.navigationItem setHidesBackButton:YES animated:YES];
    
    
}

- (void)backController:(UIButton *)button{
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 创建View
- (void)createView{
    self.isSelected = NO;
    self.investorDetailMessageView = [[InvestorDetailMessageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 150)];
    self.investorDetailMessageView.nameLabel.text = self.model.name;
    self.investorDetailMessageView.jobLabel.text = self.model.jobTitle;
    self.investorDetailMessageView.backgroundColor = [UIColor whiteColor];
    [self.investorDetailMessageView.headImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://61.135.176.43:6080/data/HeadPortrait/%@",_model.headImage]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
    self.investorDetailMessageView.groupLabel.text = @"投资人";
    self.investorDetailMessageView.focusLabel.text = [NSString stringWithFormat:@"  已关注 : %@",_model.myNoticeCount];
    self.investorDetailMessageView.funsLabel.text = [NSString stringWithFormat:@"  粉丝 : %@",_model.noticeToMeCount];

    // 主tableView
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style
                                                          :UITableViewStyleGrouped];
    self.mainTableView.tableHeaderView = self.investorDetailMessageView;
    [self.view addSubview:_mainTableView];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    [self.mainTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    [self.mainTableView registerClass:[DetailInfoCell class] forCellReuseIdentifier:NSStringFromClass( [DetailInfoCell class ])];
    [self.mainTableView registerClass:[BasicInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([BasicInfoTableViewCell class])];
    self.mainTableView.tableFooterView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
    self.mainTableView.sectionHeaderHeight = 40;
    self.mainTableView.sectionFooterHeight = 0;
    
    // 关注按钮
    self.focusButton = [UIButton  buttonWithType:UIButtonTypeSystem];
    self.focusButton.frame = CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49);
    [self.view addSubview:self.focusButton];
    [self.focusButton setTitle:@"关注" forState:UIControlStateNormal];
    [self.focusButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.focusButton.backgroundColor = COLOR_RGBA(255, 81, 90, 1);

}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.mainTableView) {
        if (section == 0) {
            UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, kScreenWidth - 20, 10)];
            titleLabel.text = @"个人简介";
            titleLabel.textAlignment = NSTextAlignmentLeft;
            titleLabel.backgroundColor = COLOR_RGBA(239, 239, 244, 1);
            return titleLabel;
        }
        else if(section == 2){
            UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, kScreenWidth - 20, 10)];
            titleLabel.text = @"投资计划";
            titleLabel.textAlignment = NSTextAlignmentLeft;
            titleLabel.backgroundColor = COLOR_RGBA(239, 239, 244, 1);
            return titleLabel;
        }
        else {
            UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 20, 10)];
            titleLabel.text = @"  ";
            titleLabel.textAlignment = NSTextAlignmentLeft;
            titleLabel.backgroundColor = COLOR_RGBA(239, 239, 244, 1);
            return titleLabel;        }
    }else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        // 计算文字的高度
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil];
        // 根据文本的内容和文本的字体进行计算高度
        // 参数一:告诉系统,文本显示的最大范围
        CGFloat width = (self.view.frame.size.width - 40);
        CGRect rect = [self.info boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        // 然后把图片的高和文本的高作为返回值返回
        return rect.size.height + 20;

    }
    else if(indexPath.section == 1){
        return 80;
    }
    else{
        return 80;
    }
}

- (void)changeSectionHeight:(NSNotification *)center{

    [self.mainTableView reloadData];

}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    else if (section == 1){
        if (self.isSelected) {
            return 3 + self.projectCount ;
        }
        else{
            return 3;
        }
    }
    else{
        return 3;
    }
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        DetailInfoCell *infoCell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([DetailInfoCell class]) forIndexPath:indexPath];
        if (self.info != nil) {
            infoCell.infoLabel.text = self.info;

        }
        else{
            infoCell.infoLabel.text = @"这个人很懒，自我介绍都还没有写哦~";
        }
        infoCell.selectionStyle = UITableViewCellSelectionStyleNone;

        return infoCell;
        
    }
    else if (indexPath.section == 1){
        if (indexPath.row < 3) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
            cell.textLabel.text = self.content[indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            return cell;
        }
        else{
            BasicInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BasicInfoTableViewCell class]) forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;

            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            FocusProjectModel *focusModel = self.modelArr[indexPath.row - 3];
            [cell.headPic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.bigtobig.com/%@",focusModel.project_logo]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
            cell.nameLabel.text = focusModel.project_name;
            cell.describe.text = focusModel.project_brief_introduction;
            return cell;
        }
        
    }
    else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class]) forIndexPath:indexPath];
        cell.textLabel.text = self.planArray[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        if (indexPath.row == 2) {
            if (self.isSelected == NO) {
                self.isSelected = YES;
                
            }
            else{
                self.isSelected = NO;
            }
        }
        else if(indexPath.row > 2){
            ProjectDetailViewController *detailVC = [[ProjectDetailViewController alloc]init];
            FocusProjectModel *focusModel = self.modelArr[indexPath.row - 3];
            detailVC.project_id = focusModel.project_id;
            [self.navigationController pushViewController:detailVC animated:YES];
            self.tabBarController.tabBar.hidden = YES;
        }
    }
    [tableView reloadData];
}
- (void)setModel:(UserMessageModel *)model{
    _model = model;
    [self.mainTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
